<script setup>
const urlHome = useUrl();
const products = ref([]);
const productId = ref(0);
const isOpenSection = ref(false);
const isOpenProduct = ref(false);
const isOpenContract = ref(false);
const sectionName = ref('');
const productName = ref('');
const username = useCookie('username');
const prodSectionSelectId = ref(0);
const sectionError = ref('');
const productError = ref('');
const omsFull = ref('');
const omsBalance = ref('');
const obFull = ref('');
const obBalance = ref('');
const pdFull = ref('');
const pdBalance = ref('');
const contractSelect = ref(0);
const contractListSelect = ref([]);
const measureName = ref('');
const warehouse = ref('');

const prodSectionSelect = computed(() => prodSections.value.find(obj => obj.id === prodSectionSelectId.value))
const prodSelect = computed(() => products.value.find(obj => obj.id === productId.value))

const filterInput = (event) => {
	console.log(event.target.value)
	let newValue = event.target.value.replace(/[^0-9.-]/g, '');

	// Разрешаем минус только на первой позиции
	if (newValue.indexOf('-') > 0) {
		newValue = newValue.replace(/-/g, '');
	}
	console.log(newValue)

	// Разрешаем только одну точку
	const parts = newValue.split('.');
	if (parts.length > 2) {
		newValue = parts[0] + '.' + parts.slice(1).join('');
	}
	console.log(newValue)

	// Если начинается с точки, добавляем 0 перед ней
	if (newValue.startsWith('.')) {
		newValue = '0' + newValue;
	}
	console.log(newValue)
	warehouse.value = newValue;
};


const { data: prodSections, refresh: prodSecRefresh } = await useFetch(`${urlHome.value}orders/product_sections/`);

async function getProdList(section_id) {
	prodSectionSelectId.value = section_id
	productId.value = 0
	const response = await $fetch(`${urlHome.value}orders/products/`, {
		query: {
			section_id: section_id
		}
	})
	if (response) {
		products.value = response
	}
}

async function addSection() {
	const response = await $fetch(`${urlHome.value}orders/product_section_add/`, {
		method: 'POST',
		body: {
			section_name: sectionName.value,
			username: username.value,
		}
	})
	if (response.ok) {
		console.log(response)
		isOpenSection.value = false;
		sectionName.value = '';
		prodSecRefresh();
	} else if (response.status === 201) {
		sectionError.value = "Такой раздел уже есть"
	}
}

async function addProduct() {
	const response = await $fetch(`${urlHome.value}orders/product_add/`, {
		method: 'POST',
		body: {
			section_id: prodSectionSelect.value.id,
			product_name: productName.value,
			username: username.value,
			measure: measureName.value,
			warehouse: warehouse.value,
		}
	})
	if (response.ok) {
		isOpenProduct.value = false;
		productName.value = '';
		getProdList(prodSectionSelect.value.id);
	} else if (response.status === 201) {
		productError.value = 'Такой продукт уже есть'
	}
}

async function addContractProduct() {
	const response = await $fetch(`${urlHome.value}orders/contract_product_add/`, {
		method: 'POST',
		body: {
			oms_full: omsFull.value,
			oms_balance: omsBalance.value,
			ob_full: obFull.value,
			ob_balance: obBalance.value,
			pd_full: pdFull.value,
			pd_balance: pdBalance.value,
			product_id: productId.value,
			contract_id: contractSelect.value,
			username: username.value,
		}
	})
	if (response) {
		console.log("addContractProduct")
		omsFull.value = ''
		omsBalance.value = ''
		obFull.value = ''
		obBalance.value = ''
		pdFull.value = ''
		pdBalance.value = ''
		contractSelect.value = 0
		isOpenContract.value = false
		getContractsProd()
	}
}

async function openContractModal() {
	await getContracts()
	isOpenContract.value = true

}

async function getContracts() {
	const response = await $fetch(`${urlHome.value}orders/get_contract_select/`, {
		query: {
			product_id: productId.value,
		}
	})
	if (response) {
		contractListSelect.value = response
	}
}

</script>
<template>
	<div>
		<div class="flex flex-col gap-2">
			<div class="flex flex-row gap-1" v-auto-animate>
				<div v-for="section in prodSections" :key="section.id">
					<div>
						<UButton color="violet" @click="getProdList(section.id)">{{ section.name }}</UButton>
					</div>
				</div>
			</div>
			<div class="flex flex-row gap-1" v-auto-animate>
				<div v-for="prod in products" :key="prod.id">
					<UButton @click="productId = prod.id"> {{ prod.name }}</UButton>
				</div>
			</div>
		</div>
		<div class="flex flex-col py-2" v-auto-animate v-if="productId > 0">
			<PbStockContracts :productId="productId" />
		</div>
	</div>
</template>